package com.sumainfor.zuul.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.zuul.dao.SysAreaDao;
import com.sumainfor.zuul.entity.SysAreaEntity;
import com.sumainfor.zuul.service.SysAreaService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 归属区域
 *
 * @author PuaChen
 * @see com.sumainfor.zuul.service.SysAreaService
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Log4j2
public class SysAreaServiceImpl extends ServiceImpl<SysAreaDao, SysAreaEntity> implements SysAreaService {

    /**
     * 查询列表的数据
     *
     * @param page
     * @param search
     * @return
     */
    @Override
    public JsonResult getTableDataList(Page<SysAreaEntity> page, String search) {
        return JsonResult.success(page.setRecords(baseMapper.selectTableDataList(page, search)));
    }

    @Override
    public JsonResult getAreaTreeList() {
        List<SysAreaEntity> listTree = baseMapper.selectAreaListTree();
        log.info("Tree Data ==> {}", listTree);
        List<SysAreaEntity> rootList = Lists.newArrayList();
        for (int i = 0; i < listTree.size(); i++) {
            SysAreaEntity entity = listTree.get(i);
            if (entity.getParentId() == 0) {
                rootList.add(entity);
            }
        }

        for (int i = 0; i < rootList.size(); i++) {
            List<SysAreaEntity> child = getChild(rootList.get(i).getAreaId(), listTree);
            rootList.get(i).setChildren(child);
        }
        log.info("Tree Handler Data ==> {}", rootList);
        return JsonResult.success(rootList);
    }


    public List<SysAreaEntity> getChild(Integer rootId, List<SysAreaEntity> allMenu) {
        //子菜单
        List<SysAreaEntity> childList = Lists.newArrayList();

        for (SysAreaEntity area : allMenu) {
            // 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
            //相等说明：为该根节点的子节点。
            if (area.getParentId().equals(rootId)) {
                childList.add(area);
            }
        }
        //递归
        for (SysAreaEntity nav : childList) {
            nav.setChildren(getChild(nav.getAreaId(), allMenu));
        }
        //如果节点下没有子节点，返回一个空List（递归退出）
        if (childList.size() == 0) {
            return Lists.newArrayList();
        }
        return childList;
    }

    /**
     * 通过归属区域编号 得到这个信息
     *
     * @param id
     * @return
     */
    @Override
    public JsonResult getAreaDataById(String id) {
        SysAreaEntity entity = baseMapper.getAreaById(id);
        return JsonResult.success(entity);
    }

}
